package com.martin.lib_base.utils

import android.accounts.NetworkErrorException
import com.google.gson.JsonSyntaxException
import com.google.gson.stream.MalformedJsonException
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * 异常工具类
 * @author ssq
 */
object ExceptionUtil {

    /**
     * 处理异常，toast提示错误信息
     */
    fun catchException(e: Throwable): String {
        e.printStackTrace()
        return when (e) {
            is HttpException -> {
                catchHttpException(e.code())
            }
            is SocketTimeoutException -> "网络请求超时,请稍后重试"
            is UnknownHostException, is NetworkErrorException -> "网络连接异常，请检查网络连接情况"
            is MalformedJsonException, is JsonSyntaxException -> "Json数据解析异常"
            is InterruptedIOException -> "服务器连接失败，请稍后重试"
            is ConnectException -> "连接服务器失败"
            else -> "未知API请求异常：${e::class.java.name}"
        }
    }

    /**
     * 处理网络异常
     */
    private fun catchHttpException(errorCode: Int): String {
        return catchHttpExceptionCode(errorCode)
    }

    /**
     * 处理网络异常
     */
    private fun catchHttpExceptionCode(errorCode: Int): String = when (errorCode) {
        in 500..600 -> "服务器异常  $errorCode"
        in 400 until 500 -> "请求异常  $errorCode"
        else -> "请求异常  $errorCode"
    }
}